package com.example.network_sdk.interceptor

import com.blankj.utilcode.util.LogUtils
import com.example.network_sdk.utils.SignUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject

class SignInterceptor : Interceptor{
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        var body = request.body()
        var buffer = Buffer()
        body!!.writeTo(buffer)
        var sign = buffer.readUtf8()
        LogUtils.e("SignInterceptor:$sign")
        var jsonObject = JSONObject(sign)
        var stringBuffer = StringBuffer()
        var keys = jsonObject.keys()
        while (keys.hasNext()) {
            stringBuffer.append(jsonObject.get(keys.next()))
        }
        var signMD5 = SignUtils.signMD5(stringBuffer.toString())
        jsonObject.put("sign", signMD5)
        LogUtils.e("SignInterceptor:${jsonObject}")
        var builder = request.newBuilder()
        var requestBody = RequestBody.create(
            MediaType.parse("application/json;charset=UTF-8"),
            jsonObject.toString()
        )
        builder.post(requestBody)
        return chain.proceed(builder.build())
    }
}